package server;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;
import java.util.Optional;

public class RequestProcessor extends Thread {

    private Socket socket;
    private Map<String, List<Wrapper>> servletMap;

    public RequestProcessor(Socket socket, Map<String, List<Wrapper>> servletMap) {
        this.socket = socket;
        this.servletMap = servletMap;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();

            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            List<Wrapper> wrapperList = servletMap.get(request.getContextPath());
            // 静态资源处理
            if (wrapperList == null) {
                response.outputHtml(request.getUrl());
            } else {
                // 动态资源servlet请求
                Optional<Wrapper> any = wrapperList.stream().findAny();
                if (!any.isPresent()) {
                    response.outputHtml(request.getUrl());
                } else {
                    Wrapper wrapper = any.get();
                    wrapper.getServlet().service(request, response);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
